package com.boot.web.controller;

import cn.hutool.core.lang.UUID;
import com.aliyuncs.exceptions.ClientException;
import com.boot.frame.jwt.JwtToken;
import com.boot.frame.qiniu.QiNiuConst;
import com.boot.frame.redis.JedisOperate;
import com.boot.utils.CaptchaUtil;
import com.boot.utils.RandomNumberUtil;
import com.boot.utils.SendSmsUtil;
import com.boot.web.dao.*;
import com.boot.web.entity.*;
import com.boot.web.vo.OperateButtonVO;
import com.boot.web.vo.app.AppCustomerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.boot.communal.response.ResponseServer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 其他接口控制器
 * @author 【zhouJie】
 * @date 2019-12-05 17:31:35
 */
@RestController
@RequestMapping("/index")
public class zhpOtherController {

    @GetMapping("/captcha/init")
    public ResponseServer captchaInit() {
        String captchaId = UUID.fastUUID().toString();
        String code = new CaptchaUtil().randomStr(4);
        JedisOperate.setObject(captchaId, code, 60);
        return ResponseServer.success("验证码初始化成功，一分钟后过期" , captchaId);
    }

    @GetMapping("/captcha/draw/{captchaId}")
    public void drawCaptcha(@PathVariable("captchaId") String captchaId, HttpServletResponse response) throws IOException {
        String code = JedisOperate.getObject(captchaId).toString();
        CaptchaUtil vCode = new CaptchaUtil(116, 36, 4, 10, code);
        response.setContentType("image/png");
        vCode.write(response.getOutputStream());
    }

    @GetMapping("/dmz/qiniu/token.json")
    public ResponseServer getQiNiuToken() {
        String qiNiuToken = QiNiuConst.getToken();
        return ResponseServer.success(qiNiuToken);
    }

    @Autowired
    private MenuPowerDao menuPowerDao;

    @Autowired
    private RolePowerDao rolePowerDao;

    /**
     * 验证操作按钮是否拥有操作权限
     * @param menuPowerId
     * @param roleId
     * @return
     */
    @GetMapping("/verify/buttonPower/{menuPowerId}/{roleId}")
    public ResponseServer verifyButtonPower(@PathVariable Integer menuPowerId, @PathVariable Integer roleId) {
        List<OperateButtonVO> voList = new ArrayList<>();
        // 根据menuPowerId获取子菜单的所有操作按钮
        List<MenuPower> mpList = menuPowerDao.queryMenuPowerByParentId(menuPowerId);
        if(mpList.size() > 0){
            // 根据roleId获取已拥有的操作权限
            List<RolePower> rpList = rolePowerDao.queryRolePowerByRoleId_1(roleId);
            if(rpList.size() > 0){
                for(MenuPower mp : mpList){
                    OperateButtonVO vo = new OperateButtonVO();
                    vo.setButtonName(mp.getName());
                    // 隐藏
                    vo.setIsShow("0");
                    for(RolePower rp : rpList){
                        // 相互比较
                        if(mp.getId().equals(rp.getPowerId())){
                            // 显示
                            vo.setIsShow("1");
                        }
                    }
                    voList.add(vo);
                }
            }
        }
        return ResponseServer.success(voList);
    }

    @Autowired
    private CustomerDao customerDao;

    /**
     * 发送短信验证码
     * @param phone
     * @param type (0=登录，1=注册，2=重置密码，3=绑定手机号)
     * @return
     * @throws ClientException
     */
    @PostMapping("/sendCode")
    public ResponseServer sendCode(String phone, String type) throws ClientException {
        if("1".equals(type) || "3".equals(type)){
            Customer customer = customerDao.queryCustomerByMobile(phone);
            if(customer != null){
                return ResponseServer.error("手机号码已存在");
            }
        }else{
            Customer customer = customerDao.queryCustomerByMobile(phone);
            if(customer == null){
                return ResponseServer.error("手机号码不存在");
            }
        }
        if(JedisOperate.exists(phone)){
            return ResponseServer.error("请60秒后再发送验证码!");
        }
        // 发送验证码并保存
        RandomNumberUtil rn = new RandomNumberUtil();
        String code = rn.verificationCode();
        JedisOperate.setObject(phone, code, 60); // 一分钟后自动过期
        SendSmsUtil.sendSms(phone, code);
        return ResponseServer.success("发送成功");
    }

    @Autowired
    private AccountDao accountDao;

    // 随机一个六位数
    public static int randoms() {
        int j = (int)((Math.random()*9+1)*100000);
        return j;
    }

    /**
     * 注册
     * @param phone
     * @param code
     * @param userId
     * @return
     */
    @PostMapping("/register")
    public ResponseServer register(String phone, String code, Integer userId){
        Customer cu = customerDao.queryById(userId);
        if(cu == null){
            return ResponseServer.error("分享链接错误! 请重试");
        }
        Customer customer = customerDao.queryCustomerByMobile(phone);
        if(customer != null){
            return ResponseServer.error("手机号码已存在");
        }
        String checkCode = JedisOperate.getObject(phone).toString();
        if (!code.equals(checkCode)) {
            return ResponseServer.error("验证码不正确");
        }
        String agentCode = cu.getAgentCode();
        Customer newCustomer = new Customer();
        if(agentCode != null && !"".equals(agentCode)){
            // 生成编号
            String str = cu.getAgentCode().substring(0,3);
            String newCode;
            do {
                newCode = str + randoms();
                if (customerDao.queryCustomerByAgentCode(newCode) == null) {
                    break;
                }
            } while (customerDao.queryCustomerByAgentCode(newCode) != null);
            newCustomer.setAgentCode(newCode);
            //newCustomer.setSign(String.valueOf(cu.getId()));
        }
        newCustomer.setParentId(cu.getId());
        BigDecimal decimal = new BigDecimal(0);
        newCustomer.setLevelId(1);
        newCustomer.setLevelCopyId(1);
        newCustomer.setLevelCopy1Id(1);
        newCustomer.setLevelCopy2Id(1);
        newCustomer.setLevelCopy3Id(1);
        newCustomer.setLevelCopy4Id(1);
        newCustomer.setIsActive("0");
        newCustomer.setIsActiveCopy("0");
        newCustomer.setIsActiveCopy1("0");
        newCustomer.setIsActiveCopy2("0");
        newCustomer.setIsActiveCopy3("0");
        newCustomer.setIsActiveCopy4("1");
        newCustomer.setAchievement(decimal);
        newCustomer.setAchievement3(decimal);
        newCustomer.setQuantityRecord(0);
        newCustomer.setOwnTotalBuy(decimal);
        newCustomer.setOwnTotalBuy3(decimal);
        newCustomer.setFiction("0");
        newCustomer.setAddUpAchievement(decimal);
        newCustomer.setAddUpUpgrade(decimal);
        newCustomer.setAddUpUpgradeFiction(decimal);
        newCustomer.setNickName(phone);
        newCustomer.setMobile(phone);
        newCustomer.setUpdateTime(new Date());
        newCustomer.setPassword("bee" + phone); // 密码
        newCustomer.setLoginName(phone); // 登录名
        newCustomer.setMasterAccount(phone); // 主账号
        newCustomer.setVerifyStatus("3");
        newCustomer.setEffective(0);
        newCustomer.setOrderQuantity(0);
        newCustomer.setIsMember("1"); // 全部默认为会员
        newCustomer.setIsDel("0");
        newCustomer.setRepeatAmount(new BigDecimal(0));
        newCustomer.setTodayArean(new BigDecimal(0));
        customerDao.save(newCustomer);
        if(accountDao.queryAccountByUserId(newCustomer.getId()) == null){
            Account account = new Account();
            account.setIntegral(0);
            account.setBliss(0);
            account.setRedPacket(0);
            account.setVoucherBalance(decimal);
            account.setUpdateTime(new Date());
            account.setUserId(newCustomer.getId());
            account.setCollageBalance(decimal);
            account.setShareBalance(decimal);
            account.setFrozenIn(decimal);
            accountDao.save(account);
            List<Coupon> couponList = couponDao.queryAll();
            if(couponList.size() > 0){
                for(Coupon cou : couponList){
                    UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(newCustomer.getId(), cou.getId());
                    if(uc == null){
                        UserCoupon newUc= new UserCoupon();
                        newUc.setCouponId(cou.getId());
                        newUc.setUserId(newCustomer.getId());
                        newUc.setUpdateTime(new Date());
                        newUc.setQuantity(0);
                        userCouponDao.save(newUc);
                    }
                }
            }
        }
        AppCustomerVO vo = new AppCustomerVO();
        BeanUtils.copyProperties(newCustomer, vo);
        vo.setParentCount(0);
        vo.setWaitingCount(0); //等开奖
        vo.setDeliveredCount(0); //待发货
        vo.setReceivedCount(0); //待收货
        vo.setAfterSalesCount(0); //代售
        vo.setCollageCount(0); //待开团
        vo.setBliss(0);
        vo.setIntegral(0);
        vo.setVoucherBalance(decimal);
        vo.setRedPacket(0);
        String token = JwtToken.createToken(newCustomer.getId());
        newCustomer.setToken(token);
        customerDao.update(newCustomer);
        return ResponseServer.success("注册成功", vo);
    }

    @Autowired
    private CouponDao couponDao;

    @Autowired
    private UserCouponDao userCouponDao;


}
